package com.keafmd.controller;

import com.keafmd.entity.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelUtil {

    public static Map<String, List<RowRangeDto>> addMerStrategy(List<Test> excelDtoList) {
        Map<String, List<RowRangeDto>> strategyMap = new HashMap<>();
        Test preExcelDto = null;
        for (int i = 0; i < excelDtoList.size(); i++) {
            Test currDto = excelDtoList.get(i);
            if (preExcelDto != null) {
                //从第二行开始判断是否需要合并
                if (currDto.getId().equals(preExcelDto.getId())) {
                    //如果id一样，则可合并一列
                    fillStrategyMap(strategyMap, "0", i);
                    //如果名字一样，合并一列
                }
                if (currDto.getName1().equals(preExcelDto.getName1())) {
                    fillStrategyMap(strategyMap, "1", i);
                }
                if (currDto.getName2().equals(preExcelDto.getName2())) {
                    fillStrategyMap(strategyMap, "2", i);
                }
//                如果后面别的属性一样，继续合并
//                if (currDto.getName().equals(preExcelDto.getName())) {
//                    fillStrategyMap(strategyMap, "2", i);
//                }
            }
            preExcelDto = currDto;
        }
        return strategyMap;
    }

    private static void fillStrategyMap(Map<String, List<RowRangeDto>> strategyMap, String key, int index) {
        List<RowRangeDto> rowRangeDtoList = strategyMap.get(key) == null ? new ArrayList<>() : strategyMap.get(key);
        boolean flag = false;
        for (RowRangeDto dto : rowRangeDtoList) {
            //分段list中是否有end索引是上一行索引的，如果有，则索引+1
            if (dto.getEnd() == index) {
                dto.setEnd(index + 1);
                flag = true;
            }
        }
        //如果没有，则新增分段
        if (!flag) {
            rowRangeDtoList.add(new RowRangeDto(index, index + 1));
        }
        strategyMap.put(key, rowRangeDtoList);
    }
}
